<?php

namespace app\common\controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use think\facade\Filesystem;

class Handle
{
    //公共上传类(商家和用户共用)
    public function commonUpload($field='file',$dirname='admin_unknown')
    {
        $file = request()->file($field);
        if (!$file) {
            return ['status' => 0, 'msg' => '上传失败，name不存在'];
        }
        
        $savename = Filesystem::disk('public')->putFile($dirname, $file);

        if ($savename) {
            $saveArr = explode('/',$savename);
            return ['status'=>1,'msg'=>'上传成功','fileName'=>$saveArr[2],'url'=> "/upload/".$savename];
        } else {
            return ['status'=>0,'msg'=>'上传失败'];
        }
    }

    //上传图片的公共方法
    public function qiniuImg($field = 'file', $dirname = 'admin_unknown')
    {
        // 存储空间名称
        $bucket = config('sysconfig.qiniu_bucket');
        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');
        // 用于签名的公钥 AK
        $accessKey = config('sysconfig.qiniu_ak');
        // 用于签名的私钥 SK
        $secretKey = config('sysconfig.qiniu_sk');
        $file = request()->file($field);
        
        if ($file) {
            // 临时文件路径
            $tmpName = $file->getRealPath();
            // 初始化鉴权对象
            $auth      = new Auth($accessKey, $secretKey);
            // 生成上传Token
            $token     = $auth->uploadToken($bucket);
            
            // 上传管理类 构建UplaodManager对象
            $uploadMgr = new UploadManager();
 
            $ext = $file->getOriginalExtension();  //TP6 后缀可以换成这个
 
            // 目录名
            if ($dirname != '') $dirname .= '/';
            // 随机文件名
            $path = $dirname . md5(microtime(true) . mt_rand(1, 1e9)) . '.' . $ext;
            $info = $uploadMgr->putFile($token, $path, $tmpName);
            if($info[0] == null){
                return ['status'=>0,'msg'=>'七牛配置错误'];
            }

            // 上传到七牛云后的新名称
            return ['status'=>1,'msg'=>'上传成功','fileName'=>$info[0]['key'],'url'=>$domain . '/' . $info[0]['key']];
        } else {
            return ['status'=>0,'msg'=>'上传失败'];
        }

    }

    // 删除七牛上的文件
    public function delQIniuImg($url)
    {
        // 存储空间名称
        $bucket = config('sysconfig.qiniu_bucket');
        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');
        // 用于签名的公钥 AK
        $accessKey = config('sysconfig.qiniu_ak');
        // 用于签名的私钥 SK
        $secretKey = config('sysconfig.qiniu_sk');

        // 构建七牛云认证对象
        $auth  = new Auth($accessKey, $secretKey);

        // 实例化 BucketManager
        $bucketManager = new BucketManager($auth);

        // 执行删除操作
        $error = $bucketManager->delete($bucket, $url);
        if ($error[0] == null) {
            return ['status'=>1,'msg'=>'删除成功'];
        } else {
            
            return ['status'=>0,'msg'=>'删除失败'];
        }
    }

    //小程序发送code
    public function sendCode($appid,$appsecret,$code){
        // 拼接请求地址
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='
            . $appid . '&secret=' . $appsecret . '&js_code='
            . $code . '&grant_type=authorization_code';
        $arr = http_url($url);
        $arr = json_decode($arr, true); //session_key openid
        return $arr;
    }

     //获取小程序码
     public function getQrCode($data=array())
     {
         $accesstoken = $this->getCacheToken();
         $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $accesstoken;
         $res = curl_post($url,$data);
         return $res;
     }

     //缓存token
    public function getCacheToken($type=0)
    {
        if (cache('access-token') && $type==0){
            $file = cache('access-token');
            if (time() < $file['expires']){
                return $file['access_token'];
            }else{
                return $this->getCacheToken(1);
            }
        }else{
            $data = array();
            $data['access_token'] = $this->getAccessToken();
            $data['expires'] = time() + 3000;
            cache('access-token',$data);
            return $data['access_token'];
        }
    }
    //获取access-token
    public function getAccessToken()
    {
        $appid = config('sysconfig.wx_appid');
        $appsecret = config('sysconfig.wx_appsecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $html = file_get_contents($url);
        $output = json_decode($html, true);
        $access_token = $output['access_token'];
        return $access_token;
    }
}
